from tkinter import *
from tkinter import ttk, font, filedialog as fd
import shutil, os, ctypes, pyglet
from fractions import Fraction
from PIL import ImageTk, Image, ImageOps, ImageDraw, ImageFont
import Program
import MyPantry
import Edit_ingredient
import Recipes_frame
from Side_frame import Side_frame
from In_refrigerator_frame import In_refrigerator_frame
from In_cabinet_frame import In_cabinet_frame
from Edit_and_add_ingredients import Edit_and_add_ingredients
from Edit_and_add_recipes import Edit_and_add_recipes
from Edit_recipe_instructions_frame import Edit_recipe_instructions_frame
from View_recipe_frame import View_recipe_frame

class Windows(Tk):
    """
    Purpose:
        main ui controller class. Opens, sets, and controls all main frames
    Instance variables:
        Program.Program.controller: makes the main controller accessible to the whole program
        self.title: sets the title of the program
        self.minsize: sets the minimum window size
        self.current_frames: list of the frames that are currently being shown
        self.frames: dictionary of all the main window frames
    Methods:
        __init__: creates all of the frames that will be used in the main
            window to simulate switching tabs/windows
        change_frames: shows the provided frame and closes background frames
        default_combo_value_clear: used to have guiding text in combo boxes that
            will be cleared when clicked
        detect_click_outside_frame: checks if a click is placed outside of
            target frame, and if it is it runs a close_menu funtion
    """

    def __init__(self, *args, **kargs):
        ctypes.windll.shcore.SetProcessDpiAwareness(True)
        Tk.__init__(self, *args, **kargs)
        Program.Program.controller = self
        self.title("Recipe Collector")
        container = Frame(self, width=570, height=670)
        self.minsize(570, 670)
        container.pack(expand=True, fill="both")
        self.current_frames = []
        self.frames = {}
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        container.rowconfigure(0, weight=1)
        container.columnconfigure(0, weight=1)
        pyglet.font.add_file(f"{os.getcwd()}\\gui\\fonts\\Roboto-Regular.ttf")
        Program.Program.roboto_font = ImageFont.truetype(
            f"{os.getcwd()}\\gui\\fonts\\Roboto-Regular.ttf",
            int(
                self.call("tk", "scaling")
                * font.nametofont("TkDefaultFont").actual()["size"]
            ),
        )
        Program.Program.resizing_title_font = font.Font(
            container, size=Program.Program.min_title_font_size, font="Roboto"
        )
        Program.Program.resizing_pantry_font = font.Font(
            container, size=Program.Program.min_pantry_font_size, font="Roboto"
        )
        for new_class in (
            MyPantry.MyPantry,
            Edit_ingredient.Edit_ingredient,
            Recipes_frame.Recipes_frame,
            Side_frame,
            In_refrigerator_frame,
            In_cabinet_frame,
            Edit_and_add_ingredients,
            Edit_and_add_recipes,
            Edit_recipe_instructions_frame,
            View_recipe_frame,
        ):
            frame = new_class(container)

            self.frames[new_class] = frame
            frame.grid(row=0, column=0, sticky="nsew")
            self.current_frames.append(frame)
        self.frames[Side_frame].grid(row=0, column=0, sticky="nsw")
        self.pack_propagate(False)
        self.bindtags((str(self), "Tk", "all", "root_window"))
        self.bind_class("root_window", "<Configure>", lambda e: Program.Program.resize_screen())
        self.update()
        with open("gui\\color settings.csv", "r") as color_settings:
            color_settings.readline()
            (
                Program.Program.light_mode,
                primary_color,
                secondary_color,
            ) = color_settings.readline().split(",")
            if Program.Program.light_mode == "True":
                Program.Program.light_mode = True
            else:
                Program.Program.light_mode = False
        if Program.Program.light_mode:
            Program.Program.change_program_colors(
                "#FFFFFF", primary_color, "#3700B3", secondary_color
            )
        else:
            Program.Program.change_program_colors(
                "#121212", primary_color, "#3700B3", secondary_color
            )
        self.frames[Side_frame].light_mode_check_var.set(Program.Program.light_mode)
        self.change_frames(MyPantry.MyPantry)

    # Saved colors
    # "#FFFFFF", "#8DC7F2", "#3700B3", "#8DF2EB

    def change_frames(self, class_frame_name, close_frames=True):
        self.frames[class_frame_name].grid()
        self.frames[class_frame_name].tkraise()
        self.update()
        if close_frames:
            for frame in self.current_frames:
                if self.frames[class_frame_name] != frame:
                    frame.grid_remove()
            self.current_frames.clear()
        self.current_frames.append(self.frames[class_frame_name])
        Program.Program.resize_screen(True)

    def default_combo_value_clear(object, combobox, string_to_match):
        if combobox.get() == string_to_match:
            combobox.set("")

    def detect_click_outside_frame(self, frame_to_detect_click, frame_to_close):
        self.bind(
            "<Button-1>",
            lambda event: frame_to_close.close_menu()
            if str(frame_to_detect_click)
            == str(self.winfo_containing(event.x_root, event.y_root))[
                : len(str(frame_to_detect_click))
            ]
            else None,
        )